package com.ktjiaoyu.service.impl;

import com.ktjiaoyu.entity.Supplier;
import com.ktjiaoyu.entity.SysRole;
import com.ktjiaoyu.entity.SysUser;
import com.ktjiaoyu.mapper.SupplierMapper;
import com.ktjiaoyu.service.SupplierService;
import com.ktjiaoyu.utils.Page;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class SupplierServiceImpl implements SupplierService {
    private static final Logger logger = LoggerFactory.getLogger(SupplierMapper.class);

    @Autowired
    private SupplierMapper supplierMapper;

    @Override
    public Page<Supplier> findPage(Supplier entity, Integer pageNo, Integer pageSize) throws Exception {
        Page<Supplier> page = null;
        try{
            page = new Page<>();
            page.setPageSize(pageSize);
            //查询总页数
            Long totalCount = supplierMapper.count(entity);
            page.setTotalCount(totalCount.intValue());
            page.setPageNo(pageNo);
            List<Supplier> data = supplierMapper.getPage(entity, page.offset(), page.getPageSize());
            page.setData(data);
        }catch (Exception e){
            logger.error("分页查询供应商列表异常", e);
            throw e;
        }
        return page;
    }

    @Override
    public boolean saveOrUpdate(Supplier entity) throws Exception {
        try {
            if (entity.getId() == null){
                //无主键则新增
                return supplierMapper.insert(entity) > 0;
            }else {
                //有主键则更新
                return supplierMapper.update(entity) > 0;
            }
        }catch (Exception e){
            logger.error("保存或修改供应商信息异常", e);
            throw e;
        }
    }

    @Override
    public List<Supplier> findAll() throws Exception {
        try{
            return supplierMapper.findAll();
        } catch (Exception e) {
            logger.error("执行SupplierServiceImpl.findAll()方法出现异常", e);
            throw e;
        }
    }

    @Override
    public Supplier getById(Long id) {
        try{
            return supplierMapper.getById(id);
        } catch (Exception e) {
            logger.error("执行SupplierServiceImpl.getById(Integer)方法出现异常", e);
            throw e;
        }
    }

    @Override
    public boolean deleteById(Long id) {
        try{
            return  supplierMapper.delete(id)> 0;
        } catch (Exception e){
            logger.error("执行SupplierServiceImpl.deleteById(Integer)方法出现异常", e);
        }
        return false;
    }

    @Override
    public Supplier findByAccount(String supCode) throws Exception {
        try{
            return supplierMapper.getByAccount(supCode);
        } catch (Exception e){
            logger.error("执行SupplierServiceImpl.findByAccount(String)方法出现异常。", e);
            throw e;
        }
    }
}
